package com.explam.springboot.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.explam.springboot.common.ResultUtil;
import com.explam.springboot.entity.User;
import com.explam.springboot.exception.ServiceException;
import com.explam.springboot.mapper.UserMapper;
import com.explam.springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        user.setPassword(SecureUtil.md5(user.getPassword()));
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        lambdaQueryWrapper.eq(User::getPassword, user.getPassword());
        User selectOne = userMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(selectOne)) {
            throw new ServiceException(ResultUtil.ERROR_CODE, "该账号不存在");
        }
        return selectOne;
    }

    /*
     * app用户注册
     * */
    @Override
    public Integer userAppRegister(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        User selectOne = userMapper.selectOne(lambdaQueryWrapper);
        if (Objects.nonNull(selectOne)) {
            throw new ServiceException(ResultUtil.ERROR_CODE, "账号已被注册！！");
        }
        String md5Password = SecureUtil.md5(user.getPassword());
        // 对密码进行加密
        user.setPassword(md5Password);
        user.setUsername(user.getUsername());
        user.setNickname(user.getUsername());
        user.setStatus(0);
        user.setIsAdmin(1);
        int insert = userMapper.insert(user);
        return insert;
    }

    /*
     * app用户登录
     * */
    @Override
    public User userAppLogin(User user) {
        user.setPassword(SecureUtil.md5(user.getPassword()));
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername());
            queryWrapper.eq(User::getPassword, user.getPassword());
            User selectOne = userMapper.selectOne(queryWrapper);
            if(Objects.isNull(selectOne)){
                throw new ServiceException(ResultUtil.ERROR_CODE,"用户尚未注册");
            }
            return selectOne;
        } catch (Exception e){
            throw new ServiceException(ResultUtil.ERROR_CODE,"登录失败");
        }
    }
}
